package com.codc;

import com.domain.LoginForm;
import com.struct.Request;
import com.struct.RequestHeader;
import com.struct.Response;
import com.struct.ResponseHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.msgpack.MessagePack;

import java.io.IOException;

/**
 * Created by Greg.chen on 2016-03-20.
 */
public class ResponseDecoder extends LengthFieldBasedFrameDecoder {

    public ResponseDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) throws IOException {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);

    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in)
            throws Exception {



        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame == null) {
            return null;
        }

        Response response = new Response();
        ResponseHeader header = new ResponseHeader();
        header.setCrcCode(frame.readInt());
        header.setLength(frame.readInt());
        header.setStateCode(frame.readInt());

        int uriLength = frame.readInt();
        byte[] uriByte = new byte[uriLength];
        frame.readBytes(uriByte);
        String uri = new String(uriByte);
        header.setUri(uri);

        response.setHeader(header);



        if (frame.readableBytes() > 4) {
            byte[]  bodyBytes;
            int length = frame.readableBytes();
            bodyBytes = new byte[length];
            frame.getBytes(frame.readerIndex(), bodyBytes, 0 , length);

            response.setBodyBytes(bodyBytes);
        }
        else{
            response.setBody(frame.readByte());
        }

        System.out.println("client receive response: " + response.toString());

        return response;
    }
}
